<!-- 编辑和添加复用 -->
<!-- 如何区分？ -->
<!-- 不可传参：row数据是表格的插槽，弹窗确实表格的兄弟组件 -->
<!-- 最好的方法是 暴露 -->
<script setup>
import { ref } from 'vue'
import { artAddService, artUpdataService } from '@/api/article'

const dialogVisible = ref(false)
const formRef = ref()
const diaForm = ref({
  cate_name: '',
  cate_alias: ''
})

const rules = {
  cate_name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    {
      pattern: /^\S{1,10}$/,
      message: '请输入1-10位的非空字符',
      trigger: 'blur'
    }
  ],
  cate_alias: [
    { required: true, message: '请输入分类别名', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]{1,10}$/,
      message: '请输入1-10位的数字或数字',
      trigger: 'blur'
    }
  ]
}

const open = (row) => {
  // console.log(row)
  dialogVisible.value = true
  diaForm.value = { ...row } //添加=>重置，添加=>回显
}

const emit = defineEmits(['success'])
const onsubmit = async () => {
  await formRef.value.validate()
  if (diaForm.value.id) {
    await artUpdataService(diaForm.value)
    ElMessage.success('编辑成功')
  } else {
    await artAddService(diaForm.value)
    ElMessage.success('添加成功')
  }
  dialogVisible.value = false
  emit('success')
}
defineExpose({
  open
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="diaForm.id ? '编辑分类' : '添加分类'"
    width="30%"
  >
    <el-form :model="diaForm" :rules="rules" ref="formRef">
      <el-form-item label="分类名称" prop="cate_name" label-width="80px">
        <el-input v-model="diaForm.cate_name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="分类别名" prop="cate_alias" label-width="80px">
        <el-input v-model="diaForm.cate_alias" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onsubmit"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
